

package cn.shengchao.examstar.pay.ohs.remote.job;

import cn.shengchao.examstar.pay.infrastructure.dao.po.PayOrder;
import cn.shengchao.examstar.pay.model.service.IOrderService;
import cn.shengchao.examstar.pay.utils.pay.PayTypeBase;
import cn.shengchao.examstar.pay.utils.pay.PayTypeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Fuzhengwei bugstack.cn @小傅哥
 * @description 检测未接收到或未正确处理的支付回调通知
 * @create 2024-07-25 07:17
 */
@Slf4j
@Component()
public class NoPayNotifyOrderJob {

    @Resource
    private IOrderService orderService;

    private Map<Long, Long> payOrderIdSum = new HashMap<>();

    @Scheduled(cron = "0/10 * * * * ?")
    public void exec() {
        try {
            List<PayOrder> orders = orderService.queryNoPayNotifyOrder();
            if (null == orders || orders.isEmpty())
                return;

            for (PayOrder order : orders) {
                // 防止重复通知
                long sum = payOrderIdSum.getOrDefault(Long.parseLong(order.getOrderId()), 0L);
                if (sum > 5) {
                    continue;
                }
                PayTypeBase payTypeBase = PayTypeEnum.getByCode(order.getPayType()).getPayType();
                long price = payTypeBase.queryPayOrder(order.getOrderId());
                if (price > 0) {
                    orderService.changeOrderPaySuccess(order.getOrderId());
                } else {
                    payOrderIdSum.put(Long.parseLong(order.getOrderId()), sum + 1);
                }
            }
        } catch (Exception e) {
            log.error("检测未接收到或未正确处理的支付回调通知失败", e);
        }
    }

}
